import axios from 'axios'
import Vue from 'vue'
import { Toast } from 'vant';
import router from '../router'

// 导入基准路径
// import { BASEURL } from './url'
// 导入token相关的方法
import { getToken } from '../utils/token'
import store from '../store/index'
// 创建一个 axios 实例
const instance = axios.create({})
// const hostURl  = process.env.NODE_ENV === 'development' ? '' : 'http://todolistapp.xyz' ;

// instance.defaults.baseURL = hostURl

// 配置请求拦截器
instance.interceptors.request.use(
  function(config) {
   const tokenString =  store.state.token ||  getToken()
    if (tokenString) {
      config.headers.token = tokenString 
    }
    return config
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function(response) {
    // Do something with response data
    if (response.data.code === 10009) {
      Toast.fail('你的登录信息失效,请重新登录');
      router.push({name:"login"})
    }
    return response.data
  },
  function(error) {
    console.log(error);
    return Promise.reject(error)
  }
)

Vue.prototype.$http = instance

// 导出设置好基准路径之后的axios
export default instance
